<?php


namespace app\api\controller;


use app\BaseController;
use edward\captcha\facade\CaptchaApi;
use think\middleware\AllowCrossDomain;

class Welcome extends BaseController
{
    protected $middleware = [AllowCrossDomain::class];

    public function index()
    {
        return redirect('/admin/welcome/login');
    }

    public function test()
    {
        return $this->msg(1);
    }

    public function login()
    {
        $post = $this->request->post();

        $username = trim($post['username']);
        $password = trim($post['password']);
        $code = trim($post['code']);
        $captcha_key = trim($post['captcha_key']);
        if (!$username) {
            return $this->msg(0, '账号不能为空', 'username');
        }
        if (!$password) {
            return $this->msg(0, '密码不能为空', 'password');
        }
        if (!$code) {
            return $this->msg(0, '验证码不能为空', 'code');
        }
        if (!$captcha_key) {
            return $this->msg(0, 'captcha_key不能为空');
        }
        if (!CaptchaApi::check($code, $captcha_key)) {
            return $this->msg(0, '验证码不正确', 'code');
        }
        $user = \think\facade\Db::name('member')->where(['username' => $username])->find();
        if (!$user) {
            return $this->msg(0, '账号不存在', 'username');
        }
        if ($user['groupid'] != 1 and $user['groupid'] != 2) {
            return $this->msg(0, '账号已经被禁用', 'username');
        }
        //密码 123456
        if (md5($password) != $user['password']) {
            return $this->msg(0, '密码错误', 'password');
        }
        $power = \think\facade\Db::name('access_back')->where(['userid' => $user['userid']])->select()->toArray();
        $power = array_map(function ($v) {
            return $v['controller'] . '/' . $v['action'];
        }, $power);
        return $this->msg(1, '登录成功', '', [
            'userid' => $user['userid'],
            'username' => $user['username'],
            'groupid' => $user['groupid'],
            'auth' => encrypt($user['userid'] . '|' . $user['username'] . '|' . $user['groupid'], config('api.auth_key')),
            'power' => $power,
        ]);
    }

}